<template>
  <div class="main" id="main">
    <div class="w3l_main_grid" >

      <div class="w3l_main_grid2" id="chat">
        <div class="sap_tabs">
          <div id="horizontalTab" style="display: block; width: 100%; margin: 0px;">
            <ul class="resp-tabs-list">
              <li class="resp-tab-item" aria-controls="tab_item-3" role="tab"><span
                class="w3ls_figure2"> </span></li>

            </ul>
            <div class="resp-tabs-container">
              <div class="tab-3 resp-tab-content" aria-labelledby="tab_item-3">
                <div class="wthree_tab_grid">
                  <h4>Chats</h4>
                  <li v-for="content  in contents">
                    <div v-if="currentUserCP===content.from">
                      <div class="agile_activity_row">
                        <div class="agile_activity_img"><img src="../assets/images/1.png"
                                                             alt=" "/><span>{{content.time}}</span></div>
                        <div class="agile_activity_img1">
                          <div class="agile_activity_sub">
                            <h5>{{currentUser}}</h5>
                            <p>{{content.content}}</p>
                          </div>
                        </div>
                        <div class="clear"></div>
                      </div>
                    </div>
                    <div v-if="currentUserCP===content.to">
                      <div class="agile_activity_row">
                        <div class="agile_activity_desc1"></div>
                        <div class="agile_activity_img2">
                          <div class="agile_activity_sub1">
                            <h5>{{toUser}}</h5>
                            <p>{{content.content}}</p>
                          </div>
                        </div>
                        <div class="agile_activity_img"><img src="../assets/images/6.png" class="img-responsive"
                                                             alt=""><span>{{content.time}}</span></div>
                        <div class="clear"></div>
                      </div>
                    </div>
                  </li>



                </div>
              </div>

            </div>
          </div>
        </div>
      </div>
    </div>
    <section id="form-search">
      <form action="#" class="chartCon">
        <input type="search" name="" id="sendMessage" placeholder="Input your message">
        <input type="button" value="Send" @click="sendMessage()">
      </form>

    </section>

    <div class="dbgao"></div>
  </div>

</template>

<script>
  import Sweetalert from '../assets/js/sweetalert-dev'
  import Global from '../components/Global.vue'

  //创建WebSocket对象
  export default{//
    mounted(){
      this.start();
      this.loadWs();
    }, data(){
      return {
        /*{
         content: "aa",
         from: "acf6a52b824343f1bf3590cc6841b7e2:Rocky",
         to: "02ecb294537d41feb52484696d12b627:root",
         time: "2017-11-28 17:21:42"
         }*/
        contents: [],
        currentUser: "",
        currentUserCP: "",
        toUser: "",
        toUserCP: "",
        message: "aa",
        count: 0
      }
    },
    methods: {
      start(){
        //这里加载页面内容
        $('#horizontalTab').easyResponsiveTabs({
          type: 'accordion', //Types: default, vertical, accordion
          width: 'auto', //auto or any width like 600px
          fit: true   // 100% fit in a container
        });
        addEventListener("load", function () {
          setTimeout(hideURLbar, 0);
        }, false);
        function hideURLbar() {
          window.scrollTo(1, 2);
        };
        this.currentUserCP = this.$route.params.id.split("+")[1];
        this.toUserCP = this.$route.params.id.split("+")[0];
        this.currentUser = this.$route.params.id.split("+")[1].split(":")[1];
        this.toUser = this.$route.params.id.split("+")[0].split(":")[1];
        var post = this;
        //显示20条聊天记录
        this.$http.jsonp(global.URL + "/getReadMessages", //跨域请求接口 去后台加载未读消息
          {
            params: {
              senderID: post.toUserCP,
              receiverID: post.currentUserCP,
            }
          }).then(function (response) {
          //  console.info(response.data)
          if(response.data.length!=0) {
            for (var i=0;i<response.data.length;i++) {
              post.contents.push(response.data[i]);
            }
          }
          post.count = post.contents.length;
        }, function (error) {
          swal("OMG", "Please login!", "error");
          post.$router.replace({path: '/login'})
        });
        this.$http.jsonp(global.URL + "/getUnreadMessages", //跨域请求接口 去后台加载未读消息
          {
            params: {
              senderID: post.toUserCP,
              receiverID: post.currentUserCP,
            }
          }).then(function (response) {
          //  console.info(response.data)
          if(response.data.length!=0) {
            for (var i=0;i<response.data.length;i++) {
              post.contents.push(response.data[i]);
            }
          }

          post.count = post.contents.length;

          //console.info(post.contents);
        }, function (error) {
          swal("OMG", "Please login!", "error");
          post.$router.replace({path: '/login'})
        });
      },
      loadWs(){

//这里开始加载聊天内容 websocket这一套
        if (Global.ws == null) {
          Global.ws = new WebSocket(global.WEB_SOKET_URL + this.$route.params.id.split("+")[1]);
        }

        Global.ws.onopen = function (evt) {
          //layer.msg("已经建立连接", {offset: 0});


        };
        var useVue = this;
        Global.ws.onmessage = function (evt) {
          /**
           * 解析后台传来的消息
           * "massage" : {
     *              "from" : "xxx",
     *              "to" : "xxx",
     *              "content" : "xxx",
     *              "time" : "xxxx.xx.xx"
     *          },
           * "type" : {notice|message},
           * "list" : {[xx],[xx],[xx]}
           */
          var dataMessage = JSON.parse(evt.data);
          var messa = dataMessage["message"];
          useVue.$set(useVue.contents, useVue.count++, messa);

        };
        Global.ws.onerror = function (evt) {
          // layer.msg("产生异常", {offset: 0});
          alert("Please refresh the page");
        };
        Global.ws.onclose = function (evt) {
          // layer.msg("已经关闭连接", {offset: 0});
          alert("Please refresh the page");
        };

      },
      /**
       * 发送信息给后台
       */
      sendMessage(){
        if (Global.ws == null) {
          Global.ws = new WebSocket(global.WEB_SOKET_URL + this.$route.params.id.split("+")[1].split(":")[0]);
        }
        var para = this.$route.params.id;
        var toID = para.split("+")[0];
        var fromID = para.split("+")[1];
        if (Global.ws == null) {
          return;
        }
        var message = $("#sendMessage").val();
        if (message == null || message == "") {
          //layer.msg("请不要惜字如金!", {offset: 0, shift: 6});
          return;
        }

        function appendZero(s) {
          return ("00" + s).substr((s + "").length);
        }  //补0函数
        function getDateFull() {
          var date = new Date();
          var currentdate = date.getFullYear() + "-" + appendZero(date.getMonth() + 1) + "-" + appendZero(date.getDate()) + " " + appendZero(date.getHours()) + ":" + appendZero(date.getMinutes()) + ":" + appendZero(date.getSeconds());
          return currentdate;
        }

        if (Global.ws == null) {
          Global.ws = new WebSocket(global.WEB_SOKET_URL + this.$route.params.id.split("+")[1].split(":")[0]);
        }
        Global.ws.send(JSON.stringify({
          message: {
            content: message,
            from: fromID,
            to: toID,      //接收人,如果没有则置空,如果有多个接收人则用,分隔
            time: getDateFull()
          },
          type: "message"
        }));
        $("#sendMessage").val("");
        setTimeout(function () {
          var chat=$("#chat");
          chat.scrollTop(chat[0].scrollHeight+50);
        },100);

      }
    },
    components: {}
  }

</script>
<style>

  @import '../assets/css/ltkj.css';
  @import '../assets/css/style.css';

</style>
